import { defineStore } from 'pinia';
import { getUserInfo, updateUserInfo, type UserInfo } from '@/api/auth';

interface UserState {
  userInfo: UserInfo;
  token: string;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userInfo: {},
    token: ''
  }),

  actions: {
    async fetchUserInfo(): Promise<void> {
      try {
        const { data } = await getUserInfo();
        this.userInfo = data;
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },

    async updateUserInfo(info: Partial<UserInfo>): Promise<boolean> {
      try {
        const { data } = await updateUserInfo(info);
        this.userInfo = { ...this.userInfo, ...data };
        return true;
      } catch (error) {
        console.error('更新用户信息失败:', error);
        return false;
      }
    },

    setToken(token: string) {
      this.token = token;
    },

    clearUserInfo() {
      this.userInfo = {};
      this.token = '';
    }
  }
});